//
//  BVTabBar.m
//  AFNetworking
//
//  Created by 崔晋 on 2019/8/11.
//

#import "BVTabBar.h"
#import "Masonry.h"

@interface BVTabBar ()

@property (nonatomic, strong) UIView *containerView;

@property (nonatomic, strong) NSArray<UIView *> *buttons;

@property (nonatomic, assign) BOOL isFirst;

@end

@implementation BVTabBar

- (void)layoutSubviews {
    [super layoutSubviews];
    [self removeLineView];
    NSMutableArray<UIView *> *buttons = [NSMutableArray array];
    [self.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj isKindOfClass:NSClassFromString(@"UITabBarButton")]) {
            [buttons addObject:obj];
        }
    }];
    self.buttons = buttons.copy;
    
    if (!self.isFirst) {
        self.isFirst = YES;
        self.containerView.frame = CGRectMake(self.buttons[0].frame.origin.x, self.buttons[0].frame.origin.y, self.buttons[0].frame.size.width, 34);
    }
}

- (instancetype)init {
    self = [super init];
    if (self) {
        [self setupViews];
    }
    return self;
}

- (void)setPage:(NSInteger)page {
    _page = page;
    [UIView animateWithDuration:0.25 animations:^{
        self.containerView.frame = CGRectMake(self.buttons[page].frame.origin.x, self.buttons[page].frame.origin.y, self.buttons[page].frame.size.width, 34);
    }];
}

- (void)setupViews {
    self.barTintColor = [UIColor whiteColor];
    self.translucent = NO;
    [self addSubview:self.containerView];
}

- (void)removeLineView {
    [self.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([NSStringFromClass(obj.classForCoder) isEqualToString:@"_UIBarBackground"]) {
            [obj.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if ([obj isKindOfClass:[UIImageView classForCoder]]) {
                    [obj removeFromSuperview];
                }
            }];
        }
    }];
}

- (UIView *)containerView {
    if (!_containerView) {
        _containerView = [[UIView alloc] initWithFrame:CGRectZero];
        _containerView.backgroundColor = [UIColor colorFromHexString:@"ed633e"];
        _containerView.layer.cornerRadius = 17;
    }
    return _containerView;
}

@end
